package com.neusoft.demo12;

import java.sql.*;

public class DBUitl {
    private Connection conn;
    private PreparedStatement pstmt;
    /**
     * 连接数据库
     */
    public Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/mysq_dbtest","root","123456");
        return conn;
    }

    /**
     * 查询
     * select * from user
     * select * from user where username=? and password=?
     * select * from user where username = ?
     */
    public ResultSet query(String sql,Object...values) throws SQLException {
        pstmt = conn.prepareStatement(sql);
        //将？替换为具体的值
        for (int i = 0; i < values.length; i++) {
            pstmt.setObject(i + 1,values[i]);
        }
        //执行查询
        ResultSet rs = pstmt.executeQuery();
        return rs;
    }



    /**
     * dml
     */
    public int dml(String sql,Object...values) throws SQLException {
        pstmt = conn.prepareStatement(sql);
        //将？替换为具体的值
        for (int i = 0; i < values.length; i++) {
            pstmt.setObject(i + 1,values[i]);
        }
        int isRight = pstmt.executeUpdate();
        return isRight;
    }
    public static void main(String[] args) {
        DBUitl db = new DBUitl();
        try {
            db.getConnection(); //连接数据库
            int isRight = db.
                    dml("insert into user(username,password) values(?,?)"
                            ,"yamaha","111111");
            System.out.println(isRight);
            //            ResultSet rs =
            //                    db.query("select * from user where username=? and password=?","fender","123456"); //执行查询
            //            while (rs.next()) {
            //                System.out.println(rs.getInt("id"));
            //                System.out.println(rs.getString("username"));
            //                System.out.println(rs.getString("password"));
            //            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 关闭资源
     */
    public void m1(int a,int b) {
        System.out.println(a + b);
    }

    public void m2 (int a,Object...values){
        for(int i = 0;i<values.length;i++){
            System.out.println(values[i]);
        }
    }


}
